import config from './config.js'


const requestApi = (url = '', method, data = {}, header = {
	'token': uni.getStorageSync('token') ? uni.getStorageSync('token') : ''
}) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.api() + url,
			method: method,
			data: data,
			header: header,
			success: (res) => {
				resolve(res.data)
				const code  = res.data.code
				if (code == 0) {

				}
				else if (code == 60002||code==60003) {
					uni.showModal({
						showCancel: false,
						title: '登录过期，请重新登录',
						content: res.data.msg,
						success: (result) => {
							console.log(result)
							if (result.confirm) {
								uni.removeStorageSync('token')
								uni.reLaunch({
									url: '/pages/users/login'
								});
							}
						}
					})
				} else if(res.data.code){
					uni.showToast({
						title:res.data.msg,
						icon:'error',
					})
				}
			},
			fail: (err) => {
				uni.showToast({
					title: "" + err.msg,
					icon: 'error'
				});
				reject(err)
			}
		})
	})
}


const requestFile = (url = '', method, data = {}, header = {
	'token': uni.getStorageSync('token') ? uni.getStorageSync('token') : ''
}) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.api() + url,
			method: method,
			data: data,
			header: header,
			responseType:'arraybuffer',
			success: (res) => {
				resolve(res.data)
			},
			fail: (err) => {
				uni.showToast({
					title: "" + err.msg,
					icon: 'none'
				});
				reject(err)
			}
		})
	})
}


export const get = (url, data = {}) => requestApi(url, 'GET', data = data)

export const post = (url, data = {}) => requestApi(url, 'POST', data = data)

export const getFile = (url, data = {}) => requestFile(url, 'GET', data = data)